/**
 * Created by xxx on 2017年9月26日.
 */
/**
 * Created by xxx on 2017/7/6.
 */
var UE;
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData: [],
            addInformation: true,
            bannerSwitch: 0,
            showImg: false,
            imgUrl: '',
            informationMenu: '',//选中菜单的id
            informationId: suixun.urlpara('informationId'),
            infT: suixun.urlpara('infT')==''?false:false,
            // infT: suixun.urlpara('infT')==''?false:true,
            tagid: 1,//是否更改菜单
            isUpdatae: false,
            updateImg: true,
            menuData: [],
            scrollTop: 0,
        }
    },
    componentDidMount: function () {
        var svar = this;
        UE = suixun.editor();//初始化富文本
        suixun.ajax(serverUrl+'/tag/listTag','',"get",function(data){//index:"'+this.state.informationMenu+'",
            if(data.code == 200){
                if(data.info.length>0){
                    for(var i = 0;i<data.info.length;i++){
                        // if(svar.state.tagid == data.info[i].id){
                        //     data.info[i].select = true;
                        // }else{
                        //
                        // }
                        data.info[i].select = false;
                        svar.state.menuData.push(data.info[i]);
                    }
                    if(svar.state.informationMenu==''){
                        data.info[0].select = true;
                        svar.state.informationMenu = data.info[0].id;
                    }
                    svar.setState({menuData:svar.state.menuData,informationMenu:svar.state.informationMenu});
                }else{
                    suixun.alert('没有查询到文章标题！');
                }
            }else{
                suixun.alert(data.msg);
            }
        });
        if(svar.state.informationId != ''){
            this.setState({addInformation:false});
            suixun.showLoding();//隐藏加载中
            suixun.ajax(serverUrl+'/article/getArticle?articleId='+svar.state.informationId,'',"get",function(data){
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    suixun.ajax(serverUrl+'/tag/listArticleTag?articleId='+svar.state.informationId,'',"get",function(taginfo) {
                        if(taginfo.code == 200){
                            $('#bannerTitle').val(data.info.title);//主题摘要
                            for(var i = 0;i<svar.state.menuData.length;i++){
                                if(svar.state.menuData[i].id == taginfo.info[0].id){
                                    svar.state.menuData[i].select = true;
                                }else{
                                    svar.state.menuData[i].select = false;
                                }
                            }
                            svar.setState({showImg:true,updateImg:false,imgUrl:data.info.litimg,tagid:taginfo.info[0].id});
                            UE.ready(function() {//编辑器初始化完成再赋值
                                UE.setContent(decodeURIComponent(data.info.content));  //赋值给UEditor
                            });
                        }else{
                            suixun.alert(data.msg);
                        }
                    });

                }else{
                    suixun.alert(data.msg);
                }
            });
            this.getGoods();
        }else{
            suixun.hideLoding();//显示加载中
        }
        this.getScroll();
    },
    /**
     * 获取商品编号
     */
    getGoods: function () {
        suixun.showLoding();//隐藏加载中
        suixun.ajax(serverUrl+'/article/getGoods.json?articleId='+this.state.informationId,'',"get",function(data) {
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                if(data.info){
                    var uuid = '';
                    for(var j = 0;j<data.info.length;j++){
                        if(uuid.indexOf(data.info[j].uuid)==-1){
                            uuid += data.info[j].uuid+',';
                        }
                    }
                    uuid = uuid.substring(0,uuid.length-1);
                }
                $("#goodsNumbers").val(uuid);
            }else{
                suixun.alert(data.msg);
            }
        }.bind(this))
    },
    /**
     * 动态监听滚动条
     */
    getScroll: function () {
        var svar = this;
        $(window).scroll(function(){
            var top = document.documentElement.scrollTop ? document.documentElement.scrollTop:document.body.scrollTop;
            svar.setState({scrollTop:top});
        });
    },
    /**
     * 保存banner广告图
     */
    saveBanner: function (ispublish) {
        var addInformation = this.state.addInformation,svar = this;
        var fileUrl = document.querySelector('#file').value;//图片是否存在
        var bannerTitle = document.querySelector('#bannerTitle').value;//主题摘要
        var goodsNumbers = $("#goodsNumbers").val();//获取商品优惠劵
        goodsNumbers = suixun.TransferString(goodsNumbers.replace(/ /g,'').replace(/	/,''));
        goodsNumbers = goodsNumbers.replace(/，/g,',');

        var content = UE.getContent();
        if((fileUrl=='' && addInformation) || (fileUrl==''  && this.state.updateImg)){
            suixun.alert('请选择图片！');
            return;
        }
        if(bannerTitle == ''){
            suixun.alert('文章标题不能为空！');
            return;
        }
        if(goodsNumbers.split(',').length>5){
            suixun.alert("最多添加5个商品!");
            return;
        }
        if(suixun.isRepeatArray(goodsNumbers.split(','))){
            suixun.alert('请勿输入重复券！');
            return;
        }
        if(content == ''){
            suixun.alert('内容不能为空！');
            return;
        }else{
            // console.log(content);
            // console.log(encodeURIComponent(content));
            // console.log(decodeURIComponent(content));

            //表格宽度超过屏幕出现滚动条
            content = content.replace(/<table/g,'<div style="overflow: auto;  width: 100%;"><table');
            content = content.replace(/<\/table>/g,'<\/table><\/div>');
            content = encodeURIComponent(content);
            // content = content.encodeHtml();
            // console.log(content.decodeHtml());
        }
        //新增操作——保存的是草稿
        if(addInformation){
            suixun.uploadImg('#file','',function (img) {
                var data = new FormData();
                data.append("litimg",img);
                data.append("title",bannerTitle);
                data.append("tagId",svar.state.informationMenu);
                data.append("content",content);
                if(goodsNumbers != ''){
                    data.append("goodsNumbers",goodsNumbers);
                }
                data.append("userId",localStorage.userId);
                suixun.showLoding();//显示加载中
                suixun.ajax(serverUrl+'/article/addArticle',data,"post",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        if(ispublish==true){
                            if(data.info){
                                svar.publishBanner(data.info.id,goodsNumbers);//拿到返回的id去修改发布
                            }else{
                                suixun.alert('保存草稿成功，发布失败!');
                            }
                        }else{
                            suixun.alert('操作成功!',function (data) {
                                if(data){
                                    if(svar.state.infT){
                                        window.location.reload()
                                    }
                                }
                            });
                        }
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            });
        }else{//修改操作
            //更换标签不用update，用另外的接口
            if(this.state.updateImg){
                suixun.uploadImg('#file','',function (img) {
                    var data = new FormData();
                    data.append("litimg",img);
                    data.append("title",bannerTitle);
                    if(ispublish==true){
                        data.append("isshow",1);
                    }else{
                        data.append("isshow",0);
                    }
                    if(goodsNumbers!=''){
                        data.append("goodsNumbers",goodsNumbers);
                    }
                    data.append("content",content);
                    data.append("id",svar.state.informationId);
                    suixun.showLoding();//显示加载中
                    suixun.ajax(serverUrl+'/article/updateArticle',data,"post",function(data){
                        suixun.hideLoding();//隐藏加载中
                        if(data.code == 200){
                            suixun.alert('操作成功!');
                            svar.changeTag();//修改tagid
                        }else{
                            suixun.alert(data.msg);
                        }
                    });
                });
            }else{
                var data = new FormData();
                data.append("title",bannerTitle);
                if(ispublish==true){
                    data.append("isshow",1);
                }else{
                    data.append("isshow",0);
                }
                if(goodsNumbers!=''){
                    data.append("goodsNumbers",goodsNumbers);
                }
                data.append("content",content);
                data.append("id",svar.state.informationId);
                suixun.ajax(serverUrl+'/article/updateArticle',data,"post",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        suixun.alert('操作成功!');
                        svar.changeTag();//修改tagid
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            }

        }
    },
    /**
     * 先保存在发布
     * @param goodsNumbers
     * @param id
     */
    publishBanner: function (id,goodsNumbers) {
        var svar= this;
        var data = new FormData();
        data.append("isshow",1);
        data.append("id",id);
        if(goodsNumbers!=''){
            data.append("goodsNumbers",goodsNumbers);
        }
        suixun.showLoding();//显示加载中
        suixun.ajax(serverUrl+'/article/updateArticle',data,"post",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                suixun.alert('操作成功!',function (data) {
                    if(data){
                        if(svar.state.infT){
                            window.location.reload()
                        }
                    }
                });
            }else{
                suixun.alert(data.msg);
            }
        });
    },
    /**
     * 修改tagid
     */
    changeTag: function () {
        var svar = this;
        if(svar.state.isUpdatae){
            var param = new FormData();
            param.append("articleId",svar.state.informationId);
            param.append("tagId",svar.state.informationMenu);
            suixun.ajax(serverUrl+'/article/changeTag',param,"post",function(taginfo) {
                if(taginfo.code == 200){

                }else{
                    suixun.alert(data.msg);
                }
            });
        }
    },
    /**
     * 选择图片
     */
    onChangFile: function () {
        var svar = this;
        var fileUrl = $("#file").val().split('\\');//注split可以用字符或字符串分割
        var fileName = fileUrl[fileUrl.length-1];//这就是要取得的图片名称
        var fileLat = fileName.substring( fileName.lastIndexOf('.')+1 );//后缀名称
        if(fileLat == "png" || fileLat == "jpg" || fileLat == "gif" || fileLat == "svg"){
            var docObj = $("#file"),src = '';
            src = window.URL.createObjectURL(docObj[0].files[0]);
            // 图片地址 后面加时间戳是为了避免缓存
            var img_url = src;
            // 创建对象
            var img = new Image();
            // 改变图片的src
            img.src = img_url;
            // 加载完成执行
            img.onload = function(){
                // 打印
                // alert('width:'+img.width+',height:'+img.height);
                // if((img.width==1125&&img.height==450)||(img.width==750&&img.height==300)){
                    svar.setState({showImg: true, imgUrl: src,updateImg: true});
                // }else{
                //     suixun.alert("图片大小错误！");
                // }
            };
            // svar.setState({showImg: true, imgUrl: src});
        }else{
            suixun.alert("请选择图片文件上传!",function (data) {
                if(data){
                    $("#file").val("");
                    svar.setState({showImg:false,imgUrl:''});
                }
            });
        }
    },
    /**
     * 加载图片
     * @returns {XML}
     */
    imgLoad: function () {
        new Viewer(document.querySelector('#showImg'));//调用图片
    },
    /**
     * 关闭图片
     * @returns {XML}
     */
    closeImg: function(){
        document.querySelector('#file').value = '';
        this.setState({showImg:false,imgUrl:'',updateImg: true});
    },
    /**
     * 点击菜单
     * @returns {XML}
     */
    onClickMenu: function (number) {
        for(var i = 0;i<this.state.menuData.length;i++){
            if(this.state.menuData[i].id == number){
                this.state.menuData[i].select = true;
            }else{
                this.state.menuData[i].select = false;
            }
        }
        if(this.state.tagid != number){
            this.state.isUpdatae = true;
        }else{
            this.state.isUpdatae = false;
        }
        this.setState({informationMenu:number,menuData:this.state.menuData,isUpdatae:this.state.isUpdatae});

    },
    /**
     * 点击预览
     */
    buttonPreview: function () {
        var goodsNumbers = $('#goodsNumbers').val();
        goodsNumbers = goodsNumbers.replace(/，/g,',');
        if(goodsNumbers==''){
            return;
        }else if(goodsNumbers.split(',').length>5){
            suixun.alert("最多添加5个商品!");
            return;
        }
        var ifr_document = document.getElementById("preview-html").contentWindow.document;
        suixun.showLoding();//显示加载中
        suixun.ajax(serverUrl+'/credits/goods/archives/getGoods.json?goodsNumbers='+goodsNumbers,'',"get",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                if(data.info&&ifr_document){
                    //设置标题
                    var goods_image = $(ifr_document).find(".goods-image");//商品编号图片
                    goods_image.html('');
                    for(var j = 0;j<data.info.length;j++){
                        goods_image.append('<img src='+JSON.parse(data.info[j].smallImg).couponImg+' />');
                    }
                }
            }else{
                suixun.alert(data.msg);
            }
        });
    },
    render: function () {
        var svar = this;
        var menuss = this.state.menuData.map(function (data,index) {
            return (
                <div className={data.select==true?'menu-list select':'menu-list'} onClick={svar.onClickMenu.bind(this,data.id)}  ><span>{data.tagname}</span></div>
            )
        });
        return (
            <div className="tableManage-body" style={{paddingBottom:"140px"}}>
                {
                    this.state.infT?
                        <header>
                            <div className="header-left" >
                                <div className="header-left-studentInfo">
                                    <a href="../businessCenter/addressTicket.html" className="header-left-button ">地区配券</a>
                                    <a href="../information/addInformation.html?infT=1" className="header-left-button showOrder">单文配券</a>
                                </div>
                            </div>
                        </header>
                            :''
                }
                <header>
                    <div  className={this.state.infT?"navg infT":"navg"} >&nbsp;&nbsp;&nbsp;&nbsp;{this.state.addInformation==true?'新增':'编辑'}资讯文章</div>
                </header>
                <div className={this.state.infT?"addBanner-bannerBody infT":"addBanner-bannerBody"} >
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title" >头图</div>
                        <div className="addBanner-bannerBody-content-text">
                            <form name="excelInputForm" id="excelInputFrom" method="post">
                                <input type="hidden" className="input-fileImg" name="filename"  />
                                <a href="javascript:;" className="file">
                                    上传图片
                                    <input type="file" onChange={this.onChangFile.bind(this)} name="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" id="file" />
                                </a>
                            </form>
                            {
                                this.state.showImg==true?
                                    <div className="uploadShowImg">
                                        <span onClick={this.closeImg.bind(this)}/>
                                        <lable><img onLoad={this.imgLoad.bind(this)} src={this.state.imgUrl} id="showImg"  /></lable>
                                    </div>:''
                            }
                            {/*<span className="inputFile-remarks">图片规格：1125像素*450像素或750像素*300像素</span>*/}
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title">文章标题</div>
                        <div className="addBanner-bannerBody-content-text">
                            <div className="content-border">
                                <input type="text" id="bannerTitle" className="input-content" placeholder="请填写主题摘要" maxLength="200"/>
                            </div>
                        </div>
                    </div>
                    <div className="body-content">
                        <div className="body-content-title noImg">商品优惠券</div>
                        <div className="body-content-text">
                            <div className="content-border content-textarea" style={{height:'70px'}}>
                                <textarea type="text" className="textarea-content" id="goodsNumbers" placeholder="请填写商品优惠券，请用逗号隔开，最多添加五个商品" maxLength="200"/>
                            </div>
                        </div>
                    </div>
                    {/*<div className="addBanner-bannerBody-content">*/}
                        {/*<div className="addBanner-bannerBody-content-title noImg">点赞数量</div>*/}
                        {/*<div className="addBanner-bannerBody-content-text">*/}
                            {/*<div className="content-border">*/}
                                {/*<input type="number" id="zanCount" className="input-content" placeholder="请填写文章点赞数量" maxLength="200"/>*/}
                            {/*</div>*/}
                        {/*</div>*/}
                    {/*</div>*/}
                    {/*<div className="addBanner-bannerBody-content">*/}
                        {/*<div className="addBanner-bannerBody-content-title noImg">已读数量</div>*/}
                        {/*<div className="addBanner-bannerBody-content-text">*/}
                            {/*<div className="content-border">*/}
                                {/*<input type="number" id="readCount" className="input-content" placeholder="请填写文章已读数量" maxLength="200"/>*/}
                            {/*</div>*/}
                        {/*</div>*/}
                    {/*</div>*/}
                    <div className="addBanner-bannerBody-content">
                        <div className="addBanner-bannerBody-content-title">文章类别</div>
                        <div className="addBanner-bannerBody-content-text">
                            {menuss}
                            {/*<div className={this.state.informationMenu=='1'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,1)}  ><span>全部</span></div>*/}
                            {/*<div className={this.state.informationMenu=='2'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,2)}  ><span>热点</span></div>*/}
                            {/*<div className={this.state.informationMenu=='3'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,3)}  ><span>亲子</span></div>*/}
                            {/*<div className={this.state.informationMenu=='4'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,4)}  ><span>亲子</span></div>*/}
                            {/*<div className={this.state.informationMenu=='5'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,5)}  ><span>亲子</span></div>*/}
                            {/*<div className={this.state.informationMenu=='6'?'menu-list select':'menu-list'} onClick={this.onClickMenu.bind(this,6)}  ><span>国学</span></div>*/}
                        </div>
                    </div>
                    <div className="addBanner-bannerBody-content" >
                        <div className="addBanner-bannerBody-content-title">内容编辑</div>
                        <div className="addBanner-bannerBody-content-text">
                            <script id="editor" type="text/plain" />
                        </div>
                    </div>
                    <div className="addBanner-foot" style={this.state.scrollTop>=290?{top:'0px'}:{top:290-this.state.scrollTop+'px'}}>
                        <span className="foot-button button-save" onClick={this.saveBanner.bind(this)}>保存草稿</span>
                        <span className="foot-button button-preview" onClick={this.buttonPreview.bind(this)}>预览</span>
                        <span className="foot-button button-save" onClick={this.saveBanner.bind(this,true)}>发布</span>
                    </div>
                </div>
                <div className="preview-layer">
                    <div className="preview-bg"/>
                    <img src="../img/icon/close_white.png" title="关闭"  className="preview_img close"  />
                    <div className="preview-phone">
                        <iframe id="preview-html" name="preview-html" src="../ueditor/preview-h5.html"/>
                    </div>
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>

            </div>
        );
    }
});
ReactDOM.render(
    <Main />,
    document.getElementById('tableManage')
);
